<?php
namespace Api\Abstracte;

abstract class Model extends \CI_Model implements \Api\interfaces\IModel
{

    protected $modelName;

    protected $baseModel;

    protected $table;

    private $_sonObject;

    public function __construct()
    {
        parent::__construct();
        $CI = & get_instance();
        $this->db = $CI->db;
    }

    /**
     * 对象详情
     *
     * @param unknown $parm            
     */
    public function detail($parm = array())
    {
        $result = $this->getDetail($parm);
        return $result;
    }

    /**
     * 列表
     *
     * @param unknown $param            
     */
    public function lists($parm = array())
    {
        $size = $parm['size'] ? $parm['size'] : 20;
        $page = $parm['page'] ? $parm['page'] : 1;
        $this->db->limit($size, ($page - 1) * $size);
        $condition = $parm;
        unset($condition['size'], $condition['page'], $condition['t'], $condition['method'], $condition['fields'], $condition['order']);
       // $this->condition($condition);
        if (isset($parm['order']))
            $this->db->order_by($param['order']);
        $idArr = $this->db->select('id')
            ->get_where($this->table)
            ->result_array();
        $lists['lists'] = array();
        if (! empty($idArr)) {
            foreach ($idArr as $val) {
                $val['fields']=$parm['fields'];
                $lists['lists'][] = $this->getDetail($val);
            }
        }
        $lists['total'] = $this->total($condition);
        return $lists;
    }

    /**
     * 统计总数
     *
     * @param unknown $parm            
     */
    public function total($parm = array())
    {
        $this->condition($parm);
        return $this->db->select('count(1) as count')
            ->get_where($this->table)
            ->row(0)->count;
    }

    /**
     * 是否存在
     *
     * @param unknown $parm            
     */
    public function isExist($id = 0)
    {
        $factroy = 'create' . ucfirst($this->baseModel);
        \Api\Factory::$factroy($id);
        return \Api\Register::get($this->baseModel . '_' . $id)->method;
    }

    /**
     * 条件
     *
     * @param unknown $parm            
     */
    public function condition($parm = array())
    {
        foreach ($parm as $key => $val) {
            if ($val) {
                $this->db->where($key, $val);
            }
        }
    }

    /**
     * 获取对象详情
     *
     * @param unknown $parm            
     */
    public function getDetail($parm = array())
    {
        $detail = array();
        $baseObject = $this->isExist($parm['id']);
        if (empty($baseObject))
            return null;
        $object = $this->_getSonObject($parm['fields']);
        foreach ($object as $key => $val) { // 遍历复杂对象的基础对象
            if (strtolower($key) != strtolower($this->baseModel)) {
                $factroy = 'create' . ucfirst($key); // 工厂方法
                $tem_id = $baseObject[$key . '_id']; // 外键名称为对象名_id(user_id)形式
                \Api\Factory::$factroy($tem_id); // 实例化对象
                $objectMethod = \Api\Register::get($key . '_' . $tem_id)->method; // 从注册树中获取对象
            } else {
                $objectMethod = $baseObject;
            }
            $detail[$key] = $this->_format($objectMethod, $val);
        }
        return $detail;
    }

    /**
     * 获取子对象
     */
    private function _getSonObject($fields = '')
    {
        return ! empty($fields) ? $this->_filtrate($fields) : $this->_queryObject();
    }

    /**
     * 处理 field获取子对象
     */
    private function _filtrate($fields = '')
    {
        $field = array();
        $_arr_field = explode(',', $fields);
        if (! empty($_arr_field)) {
            foreach ($_arr_field as $k => $v) {
                $_tmp = strtolower(trim($v));
                // 如果存在 "." 的情况
                if (strpos($_tmp, '.') != false) {
                    $_a = explode('.', $_tmp);
                    // $field['object'] = trim($_a[0]);
                    $field[trim($_a[0])][] = trim($_a[1]);
                } else {
                    $sql = "SELECT field_name FROM  " . TABLE_API_FIELD . " a LEFT JOIN " . TABLE_API_CATEGORY . " b ON b.id=a.item_id WHERE b.cate_name = '{$_tmp}'  AND a.is_necessary=1";
                    $result = $this->db->query($sql)->result_array();
                    foreach ($result as $val) {
                        $field[$_tmp][] = $val['field_name'];
                    }
                }
            }
        }
        return $field;
    }

    /**
     * 查询默认所有的子对象
     */
    private function _queryObject()
    {
        $field = array();
        $sql = "SELECT a.field_name,b.cate_name FROM " . TABLE_API_FIELD . " a LEFT JOIN " . TABLE_API_CATEGORY . " b ON a.item_id = b.id WHERE a.is_necessary=1 AND a.item_id IN (SELECT b.obj_id FROM  " . TABLE_API_CATEGORY . " a LEFT JOIN " . TABLE_API_FIELD . " b ON a.id=b.item_id  WHERE a.cate_name = '{$this->modelName}' AND a.cate_type=2 AND b.is_necessary = 1)";
        $result = $this->db->query($sql)->result_array();
        foreach ($result as $val) {
            $field[strtolower($val['cate_name'])][] = $val['field_name'];
        }
        return $field;
    }

    /**
     * 格式化输出属性
     *
     * @param unknown $method
     *            属性数组
     * @param unknown $fields
     *            过滤的属性
     * @param string $type
     *            输出类型
     * @return Ambigous <multitype:, StdClass>|multitype:unknown
     */
    private function _format($method = array(), $fields = array(), $type = 'object')
    {
        $temp = array();
        foreach ($fields as $val) {
            $temp[$val] = $method[$val];
        }
        if (empty($method) || empty($temp))
            return $type == 'array' ? array() : (object) null;
        return $temp;
    }
}